package com.cloud.api.config;

import com.cloud.api.annotation.ThreeDimensions;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

/**
 * @author 杨斌
 * 2024-08-29/8/2024
 */
public class ThreeDimensionsValidator implements ConstraintValidator<ThreeDimensions, String> {
    private int max;

    @Override
    public void initialize(ThreeDimensions constraintAnnotation) {
        this.max = constraintAnnotation.max();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (value == null || value.isEmpty()) {
            return true;  // 允许为空
        }

        String[] dimensions = value.split("\\*");

        if (dimensions.length != 3) {
            return false;  // 长度不为3，不符合规则
        }

        String concatenatedDimensions = String.join("", dimensions);

        if (concatenatedDimensions.length() > max) {
            return false;  // 拼接后长度超过max，不符合规则
        }

        for (String dimension : dimensions) {
            if (!isValidDimension(dimension)) {
                return false;  // 不是整数或小数，不符合规则
            }
        }

        return true;
    }

    private boolean isValidDimension(String dimension) {
        try {
            Double.parseDouble(dimension);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }
}


